﻿using CareerPower.Api.Controllers;
using Microsoft.AspNetCore.Mvc;
using Model;
using Model.ApiModel.ApiResult;
using Model.BaseModel.System;
using Model.Dto.System;
using Repository.Impl;
using Service.Impl;
using Utils.Redis;

namespace Api.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiExplorerSettings(GroupName = "System")]
    [ApiController]
    public class UsersController : ApiController
    {
        private readonly ISysUsersService _usersService;
        private readonly IUnitOfWork _unitOfWork;

        public UsersController(ISysUsersService usersService, IUnitOfWork unitOfWork)
        {
            _usersService = usersService;
            _unitOfWork = unitOfWork;
        }

        /// <summary>
        /// 添加修改
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResponseResult> AddUser(SysUsersDto dto)
        {
            SysUsers sysUsers = new SysUsers()
            {
                UserName = "System" + new Random().Next(),
                Address = "湖北武汉",
                AddTime = DateTime.Now,
                Age = 26,
                //Id = "9349dc5b-e445-4062-964f-0396547cb41e",
                Id = Guid.NewGuid().ToString(),
                IsDelete = 0,
                IsEnable = 0,
                LastLogin = DateTime.Now,
                LastLoginIp = "127.0.0.1",
                Password = "password",
                Sex = 1,
                Sort = 1,
            };

            var str = "{ \"ID\":33,\"Question\":\"社？（单选）\",\"A\":\"养老保险\",\"B\":\"意外保险\",\"C\":\"医疗保险\",\"Answer\":\"B\"}";

            var model = await _usersService.AddOrUpdate(sysUsers);
            return Result(true, model, "成功！");
        }

        /// <summary>
        /// 添加修改列表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<MessageModel> AddUserList()
        {
            var list = new List<SysUsers>();

            for (int i = 0; i < 2; i++)
            {
                SysUsers add = new SysUsers()
                {
                    UserName = "SystemAdd" + new Random().Next(),
                    Address = "湖北武汉",
                    AddTime = DateTime.Now,
                    Age = 26,
                    //Id = "9349dc5b-e445-4062-964f-0396547cb41e",
                    Id = Guid.NewGuid().ToString(),
                    IsDelete = 0,
                    IsEnable = 0,
                    LastLogin = DateTime.Now,
                    LastLoginIp = "127.0.0.1",
                    Password = "password",
                    Sex = 1,
                    Sort = 1,
                };
                list.Add(add);
            }

            string[] arr = { "9499A438-A2DB-9A5D-2092-7D869F9048E9", "8c174488-e983-43bb-9520-a3662b5b0f55" };

            foreach (var item in arr)
            {
                SysUsers up = new SysUsers()
                {
                    UserName = "SystemUp" + new Random().Next(),
                    Address = "湖北武汉",
                    AddTime = DateTime.Now,
                    Age = 26,
                    //Id = "9349dc5b-e445-4062-964f-0396547cb41e",
                    Id = item,
                    IsDelete = 0,
                    IsEnable = 0,
                    LastLogin = DateTime.Now,
                    LastLoginIp = "127.0.0.1",
                    Password = "password",
                    Sex = 1,
                    Sort = 1,
                };
                list.Add(up);
            }

            var res = await _usersService.AddOrUpdateList(list);

            MessageModel message = new MessageModel()
            {
                msg = "",
                data = res,
                status = 200,
                success = true
            };
            return message;
        }


        /// <summary>
        /// 分页查询搜索
        /// </summary>
        [HttpPost]
        public PageModel<SysUsers> QueryPageUser(int PageIndex = 1, int PageSize = 20, List<QueryParam> Query = null)
        {
            var conModels = _unitOfWork.GetQueryParam(Query);

            int TotalCount = 0;

            var list = _unitOfWork.db.Queryable<SysUsers>()
                        .Where(conModels)
                        .Where(t => t.IsDelete == 0)
                        .OrderByDescending(t => t.AddTime)
                        .ToPageList(PageIndex, PageSize, ref TotalCount);
            return new PageModel<SysUsers>() { data = list, dataCount = TotalCount, page = PageIndex, PageSize = PageSize };
        }


        /// <summary>
        /// 连表查询搜索
        /// </summary>
        [HttpPost]
        public PageModel<UsersLogDto> QueryPageUserLog(int PageIndex = 1, int PageSize = 20, List<QueryParam> Query = null)
        {
            var conModels = _unitOfWork.GetQueryParam(Query);
            int TotalCount = 0;
            var list = _unitOfWork.db.Queryable<Users>().LeftJoin<UserLog>((a, b) => a.Id == b.UserID && a.IsDelete == false)
                        .Select((a, b) => new UsersLogDto
                        {
                            UserId = a.Id,
                            PhoneNumber = a.PhoneNumber,
                            NickName = string.IsNullOrEmpty(a.NickName) ? a.PhoneNumber : a.NickName,
                            UserSysType = a.UserSysType,
                            CreatedTerminal = b.Terminal,
                            DateCreated = b.DateCreate,
                            Email = a.Email,
                            IP = b.Ip,
                            Title = b.Title,
                            LastLoginTime = a.LastLoginTime,
                            UserUrl = b.UserUrl
                        })
                        .MergeTable()
                        .OrderByDescending(a => a.DateCreated)
                        .Where(conModels)
                        .ToPageList(PageIndex, PageSize, ref TotalCount);
            return new PageModel<UsersLogDto>() { data = list, dataCount = TotalCount, page = PageIndex, PageSize = PageSize };
        }


        [HttpGet]
        public async Task<MessageModel> Transaction(int id)
        {
            try
            {
                _unitOfWork.BeginTran();

                var uid = Guid.NewGuid().ToString();

                var user = new SysUsers()
                {
                    Id = uid,
                    IsDelete = 0,
                    Age = 27,
                    AddTime = DateTime.Now,
                    UserName = "Test",
                    Password = "123456",
                    IsEnable = 1
                };

                var model = await _usersService.Add(user);

                //var model2 = await usersService.Add(user);

                _unitOfWork.CommitTran();

                return new MessageModel()
                {
                    msg = "",
                    data = model,
                    status = 200,
                    success = true
                };
            }
            catch (Exception ex)
            {
                _unitOfWork.RollbackTran();
                return new MessageModel()
                {
                    msg = ex.ToString(),
                    data = "报错回滚",
                    status = 400,
                    success = false
                };
            }
        }

    }
}
